package com.soft.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.soft.entity.Kanban;
import com.soft.entity.KanbanColumn;
import com.soft.entity.KanbanItem;
import com.soft.service.KanbanService;

/**
 * 看板接口（/api/kanban）：看板/列/卡片 CRUD、移动分配、详情聚合。
 */
@RestController
@RequestMapping("/api/kanban")
public class KanbanController {

    @Autowired
    private KanbanService kanbanService;
    
    /**
     * 获取所有看板
     */
    @GetMapping("/all")
    public ResponseEntity<List<Kanban>> getAllKanbans() {
    // 查询全量看板，一般用于管理端或预加载
        List<Kanban> kanbans = kanbanService.getAllKanbans();
        return ResponseEntity.ok(kanbans);
    }

    /**
     * 获取团队的所有看板
     */
    @GetMapping("/team/{teamId}")
    public ResponseEntity<List<Kanban>> getTeamKanbans(@PathVariable Integer teamId) {
    // 按团队过滤，供团队详情页使用
        List<Kanban> kanbans = kanbanService.getKanbansByTeamId(teamId);
        return ResponseEntity.ok(kanbans);
    }

    /**
     * 获取用户相关的所有看板（包括用户创建的和用户所在团队的看板）
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<List<Kanban>> getUserKanbans(@PathVariable Integer userId) {
    // 汇总与用户相关的看板（其创建或所在团队的看板）
        List<Kanban> kanbans = kanbanService.getKanbansByUserId(userId);
        return ResponseEntity.ok(kanbans);
    }

    /**
     * 创建新看板
     */
    @PostMapping
    public ResponseEntity<?> createKanban(@RequestBody Kanban kanban) {
        try {
            // 组装并创建看板（团队ID/名称等在服务层校验）
            Kanban createdKanban = kanbanService.createKanban(kanban);
            return ResponseEntity.ok(createdKanban);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("创建看板失败: " + e.getMessage());
        }
    }

    /**
     * 获取看板详情（包含列和卡片）
     */
    @GetMapping("/{kanbanId}/detail")
    public ResponseEntity<Map<String, Object>> getKanbanDetail(@PathVariable Integer kanbanId) {
    // 聚合看板→列→卡片等信息，便于前端一次性渲染
        Map<String, Object> kanbanDetail = kanbanService.getKanbanDetail(kanbanId);
        return ResponseEntity.ok(kanbanDetail);
    }

    /**
     * 添加看板列
     */
    @PostMapping("/{kanbanId}/column")
    public ResponseEntity<?> addColumn(@PathVariable Integer kanbanId, @RequestBody KanbanColumn column) {
        try {
            // 绑定看板ID并创建列
            column.setKanbanId(kanbanId);
            KanbanColumn createdColumn = kanbanService.addColumn(column);
            return ResponseEntity.ok(createdColumn);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("添加列失败: " + e.getMessage());
        }
    }

    /**
     * 移动卡片到不同列
     */
    @PutMapping("/item/{itemId}/move")
    public ResponseEntity<?> moveItem(@PathVariable Integer itemId, @RequestBody Map<String, Object> moveData) {
        try {
            // 从请求体解析目标列及新序号
            Integer newColumnId = (Integer) moveData.get("columnId");
            Integer newSortOrder = (Integer) moveData.get("sortOrder");
            // 执行移动（服务层负责范围/权限/排序校验）
            kanbanService.moveItem(itemId, newColumnId, newSortOrder);
            return ResponseEntity.ok("移动成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("移动失败: " + e.getMessage());
        }
    }

    /**
     * 为看板添加任务卡片
     */
    @PostMapping("/{kanbanId}/item")
    public ResponseEntity<?> addItem(@PathVariable Integer kanbanId, @RequestBody KanbanItem item) {
        try {
            // 绑定看板ID并新增卡片，可能与某个日程关联
            item.setKanbanId(kanbanId);
            KanbanItem createdItem = kanbanService.addItem(item);
            return ResponseEntity.ok(createdItem);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("添加卡片失败: " + e.getMessage());
        }
    }

    /**
     * 分配任务给成员
     */
    @PutMapping("/item/{itemId}/assign")
    public ResponseEntity<?> assignItem(@PathVariable Integer itemId, @RequestParam Integer assigneeId) {
        try {
            // 分派给成员，服务层可记录 assign_time 等审计字段
            kanbanService.assignItem(itemId, assigneeId);
            return ResponseEntity.ok("分配成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("分配失败: " + e.getMessage());
        }
    }

    /**
     * 删除看板
     */
    @DeleteMapping("/{kanbanId}")
    public ResponseEntity<?> deleteKanban(@PathVariable Integer kanbanId) {
        try {
            // 删除看板（可能需要级联删除列/卡片，交由服务层处理）
            kanbanService.deleteKanban(kanbanId);
            return ResponseEntity.ok("删除成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除失败: " + e.getMessage());
        }
    }

    /**
     * 删除列
     */
    @DeleteMapping("/column/{columnId}")
    public ResponseEntity<?> deleteColumn(@PathVariable Integer columnId) {
        try {
            // 删除列（若存在卡片需考虑迁移或级联，交由服务层）
            kanbanService.deleteColumn(columnId);
            return ResponseEntity.ok("删除成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除失败: " + e.getMessage());
        }
    }

    /**
     * 更新看板名称/描述
     */
    @PutMapping("/{kanbanId}")
    public ResponseEntity<?> updateKanban(@PathVariable Integer kanbanId, @RequestBody Map<String, Object> body) {
        try {
            // 解析可更新字段：名称与描述（允许仅更新其中之一）
            String name = body != null && body.get("kanbanName") != null ? String.valueOf(body.get("kanbanName")) : null;
            String desc = body != null && body.get("description") != null ? String.valueOf(body.get("description")) : null;
            if ((name == null || name.trim().isEmpty()) && desc == null) {
                return ResponseEntity.badRequest().body("没有可更新的字段");
            }
            // 委托服务层执行更新
            kanbanService.updateKanban(kanbanId, name, desc);
            return ResponseEntity.ok("更新成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户管理的团队看板
     */
    @GetMapping("/managed/{userId}")
    public ResponseEntity<List<Kanban>> getManagedKanbans(@PathVariable Integer userId) {
    // 查询用户作为leader/管理员管理的看板
        List<Kanban> kanbans = kanbanService.getManagedKanbans(userId);
        return ResponseEntity.ok(kanbans);
    }

    /**
     * 获取用户参加的团队看板
     */
    @GetMapping("/joined/{userId}")
    public ResponseEntity<List<Kanban>> getJoinedKanbans(@PathVariable Integer userId) {
    // 查询用户参与团队下的看板
        List<Kanban> kanbans = kanbanService.getJoinedKanbans(userId);
        return ResponseEntity.ok(kanbans);
    }
}
